<?php
if (! defined ( 'BASEPATH' ))
    exit ( 'No direct script access allowed' );

class Registrasi extends Controller {
    public function __construct() {
        parent::__construct ();
        $this->_data = array ();
        $this->load->model ( 'registrasi_model' );
        isController('registrasi','registrasi');
    }
    protected function _view($template, $data = array(), $result = false) {
        if ($data && is_array ( $data )) {
            return $this->load->view ( $template, $data, $result );
        }
        return $this->load->view ( $template, $this->_data, $result );
    }
    public function index() {
        redirect ( 'klinik/registrasi/view' );
    }
    protected function _executeView() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'action' ) );
        // delete action
        if (isAccess('registrasi','registrasi','delete') && $array ['action'] == 'delete' && $array ['id']) {
            if ($this->registrasi_model->delete($array['id'])) {
                $this->_data['errorMessage'] =  'Berhasil Delete Pasien' ;
                $this->_data['isSuccess'] =  true ;
            } else {
                $this->_data['errorMessage'] =  'Gagal Delete Pasien' ;
            }
        }
    }
    public function view() {
    	if (! isAccess ( 'registrasi', 'registrasi', 'view'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'status', 'action', 'page' ) );
        $this->_executeView ();
        $array['page'] = (int) $array['page'];

        //Where
        $where = array();
        $where['rmStatus'] = array('Tunggu');
        $where['rmTglMulai'] = date('Y-m-d');
        $total = $this->registrasi_model->getCount($where);
        
        $this->load->library('pagination');
        if (($array['page'] + 1) > $total)
            $array['page'] = 0;
        $limit = $this->config->item('klinik_limit');
        $config = $this->config->item('paging');
        $config['base_url'] = site_url('klinik/registrasi/view/page/');
        $config['uri_segment'] = 4;
        $config['total_rows'] = $total;
        $config['per_page'] = $limit;
        
        $this->pagination->initialize($config);
        $this->_data['paging'] =  $this->pagination->create_links();
        
        $dataView = $this->registrasi_model->getList($where, $limit, $array['page']);
        $this->_data['dataView'] = $dataView;
        $this->_data['uri_to_assoc'] = $array;

        $this->_view ( 'klinik/regView' );
    }
    protected function _executeRegBaru() {
        $array = $this->uri->uri_to_assoc ( 3, array ('kode', 'action' ) );
        
        if ($this->input->post ( 'submit' ) == 'Simpan' && $this->input->post ( 'kirim' ) == 'kirim') {
            
        	$where = array();
        	$where['rmTglMulai'] = date('Y-m-d');
	        $rmNoUrut = $this->registrasi_model->getNoUrut( $where );
	        
	        $pasienTipe = trim ( $this->input->post ( 'pasienTipe' ) );
        	$pasienNama = trim ( $this->input->post ( 'pasienNama' ) );
            $pasienJenKel = trim ( $this->input->post ( 'pasienJenKel' ) );
            $pasienTmpLahir = trim ( $this->input->post ( 'pasienTmpLahir' ) );
            $pasienTglLahir = trim ( $this->input->post ( 'pasienTglLahir' ) );
            
            $pasienNoTelp = trim ( $this->input->post ( 'pasienNoTelp' ) );
            $pasienAlamat = trim ( $this->input->post ( 'pasienAlamat' ) );
            $pasienPekerjaan = trim ( $this->input->post ( 'pasienPekerjaan' ) );
            $pasienAgama = trim ( $this->input->post ( 'pasienAgama' ) );
            $pasienKawin = trim ( $this->input->post ( 'pasienKawin' ) );
            
			$pasienGolDarah = trim ( $this->input->post ( 'pasienGolDarah' ) );
			$pasienNamaPenanggung = trim ( $this->input->post ( 'pasienNamaPenanggung' ) );
			$pasienAlamatPenanggung = trim ( $this->input->post ( 'pasienAlamatPenanggung' ) );
			$pasienHubunganPenanggung = trim ( $this->input->post ( 'pasienHubunganPenanggung' ) );
			
            //Get Kode Pasien
//            $dataKode = array();
//            $dataKode['nourut'] = $rmNoUrut;
//            $dataKode['jenkel'] = $pasienJenKel;
//            $pasienKode = pasienKode($dataKode);
            
            $data = array ();
            $data ['pasienKode'] = PasienKode();
            
            $data ['pasienTipe'] = $pasienTipe;
            $data ['pasienNama'] = $pasienNama;
            $data ['pasienJenKel'] = $pasienJenKel;
            $data ['pasienTmpLahir'] = $pasienTmpLahir;
            $data ['pasienTglLahir'] = $pasienTglLahir;
            
            $data ['pasienNoTelp'] = $pasienNoTelp;
            $data ['pasienAlamat'] = $pasienAlamat;
            $data ['pasienPekerjaan'] = $pasienPekerjaan;
            $data ['pasienAgama'] = $pasienAgama;
            $data ['pasienKawin'] = $pasienKawin;
            
            $data ['pasienGolDarah'] = $pasienGolDarah;
            $data ['pasienNamaPenanggung'] = $pasienNamaPenanggung;
            $data ['pasienAlamatPenanggung'] = $pasienAlamatPenanggung;
            $data ['pasienHubunganPenanggung'] = $pasienHubunganPenanggung;
            
            $errors = array ();
            if (empty ( $rmNoUrut ))
                $errors [] = 'Input No Urut';
                
            if (empty ( $pasienTipe ))
                $errors [] = 'Input Tipe Pasien';    
            if (empty ( $pasienNama ))
                $errors [] = 'Input Nama';
            if (empty ( $pasienJenKel ))
                $errors [] = 'Input Jenis Kelamin';     
            if (empty ( $pasienTmpLahir ))
                $errors [] = 'Input Tempat Lahir';    
            if (empty ( $pasienTglLahir ))
                $errors [] = 'Input Tanggal Lahir';
                
            if (empty ( $pasienNoTelp ))
                $errors [] = 'Input No Telp';
            if (empty ( $pasienAlamat ))
                $errors [] = 'Input Alamat';
            if (empty ( $pasienPekerjaan ))
                $errors [] = 'Input Pekerjaan';
            if (empty ( $pasienAgama ))
                $errors [] = 'Input Agama';    
			if (empty ( $pasienKawin ))
                $errors [] = 'Input Kawin';
                
            if (empty ( $pasienGolDarah ))
                $errors [] = 'Input Gol Darah';
            if (empty ( $pasienNamaPenanggung ))
                $errors [] = 'Input Nama Penanggung';
            if (empty ( $pasienAlamatPenanggung ))
                $errors [] = 'Input Nama Penanggung';
            if (empty ( $pasienHubunganPenanggung ))
                $errors [] = 'Input Hubungan';
  
            if ($errors) {
                $this->_data['errorMessage'] =  implode ( '<br />', $errors ) ;
            } else {
            	$this->load->model('pasien_model');
            	
	            if ($this->pasien_model->add ( $data )) {
	            	$pasienId = $this->db->insert_id();
	            	
	            	$data2 = array();
	            	$data2['rmKode'] = RMKode();
	            	$data2['pasienId'] = $pasienId;
	            	$data2['userId'] = getUserId();
	            	$data2['rmNoUrut'] = $rmNoUrut;
	            	$data2['rmTglMulai'] = date('Y-m-d H:i:s');
	            	$data2['rmStatus'] = 'Tunggu';
	            	
	            	$this->registrasi_model->add ( $data2 );
	            	
	                $this->_data['errorMessage'] =  'Berhasil Registrasi Pasien' ;
	                $_POST = array();
	                $this->_data['isSuccess'] =  true ;
	            } else {
	                $this->_data['errorMessage'] =  'Gagal Registrasi Pasien' ;
	            }	
            }
        
        }
    }

    public function regBaru() {
    	if (! isAccess ( 'registrasi', 'registrasi', 'regbaru'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('action' ) );

        $this->_data['listTipePasien'] = $this->config->item('listTipePasien');
        $this->_data['listJenKel'] = $this->config->item('listJenKel');
        $this->_data['listAgama'] = $this->config->item('listAgama');
        $this->_data['listKawin'] = $this->config->item('listKawin');
        $this->_data['listGolDarah'] = $this->config->item('listGolDarah');
        
        $this->_executeRegBaru ();
        $this->_view ( 'klinik/regBaru' );
    }
    
	protected function _executeRegMember() {
        $array = $this->uri->uri_to_assoc ( 3, array ('kode', 'action' ) );
        
        if ($this->input->post ( 'submit' ) == 'Simpan' && $this->input->post ( 'kirim' ) == 'kirim') {
            //Data
            $this->load->model('pasien_model');
            
            $whr = array();
			$whr['field'] = 'pasienKode';
			$whr['value'] = trim ( $this->input->post ( 'pasienKode' ) );
            $getPasien = $this->pasien_model->getJson($whr);
            $pasienId = isset($getPasien[0]['pasienId']) ? $getPasien[0]['pasienId'] : '';
        	
        	$where = array();
        	$where['rmTglMulai'] = date('Y-m-d');
	        $rmNoUrut = $this->registrasi_model->getNoUrut( $where );
            
            //Get Kode Pasien
            $data = array ();
            $data ['rmKode'] = RMKode();
            $data ['pasienId'] = $pasienId;
            $data ['userId'] = getUserId();
            $data ['rmNoUrut'] = $rmNoUrut;
            $data ['rmTglMulai'] = date('Y-m-d H:i:s');
            $data ['rmStatus'] = 'Tunggu';
	            	
            $errors = array ();
            if (empty ( $rmNoUrut ))
                $errors [] = 'Input No Urut';
            if (empty ( $pasienId ))
                $errors [] = 'Pasien Tidak Ditemukan';    
  
            if ($errors) {
                $this->_data['errorMessage'] =  implode ( '<br />', $errors ) ;
            } elseif ($this->registrasi_model->add ( $data )) {
                $this->_data['errorMessage'] =  'Berhasil Registrasi Pasien' ;
                unset($_POST);
                $this->_data['isSuccess'] =  true ;  
            } else {
                $this->_data['errorMessage'] =  'Gagal Registrasi Pasien' ;
            }
        
        }
    }

    public function regMember() {
    	if (! isAccess ( 'registrasi', 'registrasi', 'regmember'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('action' ) );

        $this->_data['listJenKel'] = $this->config->item('listJenKel');

        $this->_executeRegMember ();
        $this->_view ( 'klinik/regMember' );
    }

    protected function _executeProses($dataPost=array()) {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'action' ) );
        
        if ($this->input->post ( 'submit' ) == 'Proses' && $this->input->post ( 'kirim' ) == 'kirim') { 
			$alat = $this->input->post ( 'alat' );
			$pemeriksaan = $this->input->post ( 'pemeriksaan' );
			$dokterId = trim ( $this->input->post ( 'dokterId' ) );
            $rmKeluhan = trim ( $this->input->post ( 'rmKeluhan' ) );
            $rmDiagnosa = trim ( $this->input->post ( 'rmDiagnosa' ) );
            $rmKeterangan = trim ( $this->input->post ( 'rmKeterangan' ) );
	            
            $errors = array ();
            if (empty ( $dokterId ))
                $errors [] = 'Pilih Dokter';
            if (empty ( $rmKeluhan ))
                $errors [] = 'Input Keluhan / Gejala';
            if (empty ( $rmDiagnosa ))
                $errors [] = 'Input Diagnosa';    
            if (empty ( $alat ))
                $errors [] = 'Pilih Alat';
            if (empty ( $pemeriksaan ))
                $errors [] = 'Pilih Pemeriksaan';       
                
            if ($errors) {
                $this->_data['errorMessage'] =  implode ( '<br />', $errors ) ;
            } else {
				//RM Alat
					$rmAlat = isset($dataPost['rmAlat']) ? $dataPost['rmAlat'] : array();
									
					//Delete Jika Tidak Sudah Dipilih
					if($rmAlat) foreach($rmAlat as $key=>$alId) {
						if( !in_array($alId,$alat) ) {
							//Delete
							$whereAlat[$key] = array();
							$whereAlat[$key]['rmId'] = $array['id'];
							$whereAlat[$key]['alatId'] = $alId;
							$this->alat_model->deleteRM($whereAlat[$key]);
							
							//Update Stock (Add Stock)
							$this->alat_model->addStock($alId);
						}
						
					}
					
					//Insert yg Baru Dipilih
	            	if($alat) foreach($alat as $key=>$alatId) {
	            		
						if( !in_array($alatId,$rmAlat) ) {
							//Get
							$getAlat[$key] = $this->alat_model->get($alatId);
							
							//Data
							$dataAlat[$key] = array();
							$dataAlat[$key]['rmId'] = $array['id'];
							$dataAlat[$key]['alatId'] = $alatId;
							
							$rmAlatHarga[$key] = get_data($getAlat[$key],'alatHarga');
							$dataAlat[$key]['rmAlatHarga'] = $rmAlatHarga[$key];
							
							$rmAlatHargaJual[$key] = get_data($getAlat[$key],'alatHargaJual');
							$dataAlat[$key]['rmAlatHargaJual'] = $rmAlatHargaJual[$key];
							
							//Insert
							$this->alat_model->addRM($dataAlat[$key]);
							
							//Update Stock (Reduce Stock)
							$this->alat_model->delStock($alatId);
						}
						
					}
				//End RM Alat	
				
	        	//RM Pemeriksaan
	            	$rmPemeriksaan = isset($dataPost['rmPemeriksaan']) ? $dataPost['rmPemeriksaan'] : array();
									
					//Delete Jika Tidak Sudah Dipilih
					if($rmPemeriksaan) foreach($rmPemeriksaan as $key2=>$pemId) {
						if( !in_array($pemId,$pemeriksaan) ) {
							//Delete
							$wherePem[$key2] = array();
							$wherePem[$key2]['rmId'] = $array['id'];
							$wherePem[$key2]['pemeriksaanId'] = $pemId;
							$this->pemeriksaan_model->deleteRM($wherePem[$key2]);
						}
						
					}
					
					//Insert yg Baru Dipilih
					if($pemeriksaan) foreach($pemeriksaan as $key2=>$pemeriksaanId) {
						
						if( !in_array($pemeriksaanId,$rmPemeriksaan) ) {
							//Get
							$getPemeriksaan[$key2] = $this->pemeriksaan_model->get($pemeriksaanId);
							
							//Data
							$dataPemeriksaan[$key2] = array();
							$dataPemeriksaan[$key2]['rmId'] = $array['id'];
							$dataPemeriksaan[$key2]['pemeriksaanId'] = $pemeriksaanId;
							
							$rmPemeriksaanHarga[$key2] = get_data($getPemeriksaan[$key2],'pemeriksaanHarga');
							$dataPemeriksaan[$key2]['rmPemeriksaanHarga'] = $rmPemeriksaanHarga[$key2];
							
							//Insert
							$this->pemeriksaan_model->addRM($dataPemeriksaan[$key2]);
						}
					}
				//End RM Pemeriksaan
							
	        	//RM Detail
	            $dataDetail = array ();
	            $dataDetail ['userId'] = getUserId();
	            $dataDetail ['dokterId'] = $dokterId;
				$dataDetail ['rmKeluhan'] = $rmKeluhan;
				$dataDetail ['rmDiagnosa'] = $rmDiagnosa;
				$dataDetail ['rmKeterangan'] = $rmKeterangan;
				
				//Get Biaya
				$where = array();
				$where['rmId'] = $array['id'];
				
				$biayaAlat = $this->alat_model->getBiaya($where);
				$biayaPemeriksaan = $this->pemeriksaan_model->getBiaya($where);
				
				$totalBiaya = $biayaAlat + $biayaPemeriksaan;
				$dataDetail ['rmTotalBiaya'] = $totalBiaya;
				
				//Insert Detail
				$getRMDetail = $this->registrasi_model->get($array['id']);
				if( !empty($getRMDetail['dokterId']) ) {
					$this->registrasi_model->updateRM($array['id'], $dataDetail);
				} else {
					$dataDetail ['rmId'] = $array['id'];
					$this->registrasi_model->addRM($dataDetail);
				}
				
				//Data RM
				if( get_data($getRMDetail,'rmStatus') == 'Tunggu' ) {
					//Update Status
					$data3 = array();
					$data3['rmTglSelesai'] = date('Y-m-d H:i:s');
					$data3['rmStatus'] = 'Selesai';
		            $this->registrasi_model->update ( $array['id'], $data3 );
		            
		            //Update Jml RJ Pasien
		            $this->registrasi_model->updateJmlRJ ( get_data($getRMDetail,'pasienId') );
		            
		            //Update Last RJ Pasien
		            $this->load->model('pasien_model');
		            
					$data4 = array();
					$data4['pasienLastRJ'] = date('Y-m-d H:i:s');
		            $this->pasien_model->update ( get_data($getRMDetail,'pasienId'), $data4 );
				}
	            
	            $this->_data['errorMessage'] =  'Berhasil Ubah Rekam Medis Pasien' ;
	            unset($_POST);
	            $this->_data['isSuccess'] =  true ;    
	            
            }
        }    
    }

    public function proses() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'pasienId', 'from', 'action') );
        if ( !$array ['id'] || !$array['from'])
            show_404 ();
  
        //Load
        $this->load->model( array('dokter_model', 'alat_model', 'pemeriksaan_model') );
            
        //Data General
        $dataPasien = $this->registrasi_model->get ( $array ['id'] );
        $this->_data['dataPasien'] = $dataPasien;    
        if (! $dataPasien)
            show_404 ();

        //Dokter
        $listDokter = $this->dokter_model->getList(10, 0);
        $this->_data['listDokter'] = $listDokter;
        
        //Alat
        $listAlat = $this->alat_model->getList(100, 0, array('stock'=>1));
        $this->_data['listAlat'] = $listAlat;

        $dataAlat = $this->alat_model->getListRM( array('rmId'=>$array['id']) );
        $rmAlat = array();
        if($dataAlat) foreach($dataAlat as $v) {
        	$rmAlat[] = get_data($v,'alatId');
        }
        $this->_data['rmAlat'] = $rmAlat;
        
        //Pemeriksaan
        $listPemeriksaan = $this->pemeriksaan_model->getList(100, 0);
        $this->_data['listPemeriksaan'] = $listPemeriksaan;
            
        $dataPemeriksaan = $this->pemeriksaan_model->getListRM( array('rmId'=>$array['id']) );
    	$rmPemeriksaan = array();
        if($dataPemeriksaan) foreach($dataPemeriksaan as $v2) {
        	$rmPemeriksaan[] = get_data($v2,'pemeriksaanId');
        }
        $this->_data['rmPemeriksaan'] = $rmPemeriksaan;
        
        //Data Post
        $dataPost = array();
        $dataPost['rmAlat'] = $rmAlat;
        $dataPost['rmPemeriksaan'] = $rmPemeriksaan;
        
        $this->_executeProses($dataPost);
        if( isset($array['action']) && $array['action'] == 'status'  )
        	$this->_executeChangeStatus();
        	
        $this->_data['uri'] = $array;
        $this->_view ( 'klinik/regProses' );
    }
    
    //Change Status
    protected function _executeChangeStatus() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id') );
        if (! $array ['id'])
            show_404 ();
            
        $data = array();
		$data['rmTglSelesai'] = date('Y-m-d H:i:s');
		$data['rmStatus'] = 'Selesai';
        
        if( $this->registrasi_model->update ( $array['id'], $data ) ) {
        	$this->_data['errorMessage'] =  'Berhasil Edit Status Pasien' ;
	        unset($_POST);
	        $this->_data['isSuccess'] =  true ;  
        } else {
        	$this->_data['errorMessage'] =  'Berhasil Edit Status Pasien' ;
        }
    }

    public function preview() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'from', 'pasienId', 'action') );
 		if ( !$array ['id'] || !$array['from'])
            show_404 ();
            
        //Load
        $this->load->model( array('alat_model', 'pemeriksaan_model') );
            
        //Data General
        $dataPasien = $this->registrasi_model->get ( $array ['id'] );
        $this->_data['dataPasien'] = $dataPasien;    
        if (! $dataPasien)
            show_404 ();
            
        //Data Alat
        $dataAlat = $this->alat_model->getListRM( array('rmId'=>$array['id']) );    
        $this->_data['dataAlat'] = $dataAlat;
        
        //Data Alat
        $dataPemeriksaan = $this->pemeriksaan_model->getListRM( array('rmId'=>$array['id']) );    
        $this->_data['dataPemeriksaan'] = $dataPemeriksaan;
        
        $this->_data['uri'] = $array;
        $this->_view ( 'klinik/regPreview' );
    }
   
}